package org.jflame.web;

import org.jflame.commons.json.JsonHelper;
import org.jflame.commons.model.CallResult;

import java.io.IOException;
import java.io.PrintWriter;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

public class RedirectStrategy {

    private final String redirectUrl;
    private final Object responseEntity;// json返回
    private int httpStatus = HttpServletResponse.SC_OK;

    public RedirectStrategy(String redirectUrl, Object responseEntity) {
        this.redirectUrl = redirectUrl;
        if (responseEntity == null) {
            this.responseEntity = JsonHelper.toJson(CallResult.ok(redirectUrl));// 返回json由前端转向
        } else {
            this.responseEntity = responseEntity;
        }
    }

    public void redirect(HttpServletRequest request, HttpServletResponse response) throws IOException {
        response.setStatus(httpStatus);
        if (redirectUrl == null) {
            if (WebUtils.isJsonRequest(request) || WebUtils.isAjaxRequest(request)) {
                WebUtils.outJson(response, responseEntity);
            } else {
                PrintWriter out = response.getWriter();
                out.print(responseEntity);
            }
            response.flushBuffer();
        } else {
            response.sendRedirect(response.encodeRedirectURL(redirectUrl));
        }
    }

    public RedirectStrategy httpStatus(int httpStatus) {
        this.httpStatus = httpStatus;
        return this;
    }

}
